package cn.tedu.imop.marketing.service.impl;

import cn.tedu.imop.common.pojo.PageData;
import cn.tedu.imop.marketing.dao.repository.CouponCodeRepository;
import cn.tedu.imop.marketing.dao.repository.CouponRepository;
import cn.tedu.imop.marketing.entity.Coupon;
import cn.tedu.imop.marketing.entity.CouponCode;
import cn.tedu.imop.marketing.service.CouponService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
public class CouponServiceImpl implements CouponService {
    private CouponRepository couponRepository;
    private CouponCodeRepository couponCodeRepository;
    public CouponServiceImpl(CouponRepository couponRepository, CouponCodeRepository couponCodeRepository) {
        this.couponRepository = couponRepository;
        this.couponCodeRepository = couponCodeRepository;
    }
    @Transactional(readOnly = false,isolation = Isolation.READ_COMMITTED,rollbackFor = RuntimeException.class)
    @Override
    public Boolean createCoupon(Coupon coupon) {
        //添加优惠卷自身信息
        couponRepository.insertCoupon(coupon);
        //添加优惠卷卷码实例(一条优惠卷记录对应着多条优惠卷卷码实例)
        insertCouponCode(coupon);
        //远程调用库存服务,初始化优惠卷库存（先做钩子）
        initCouponStock(coupon);
        return true;
    }
    private void initCouponStock(Coupon coupon){
        //......
    }
    private void insertCouponCode(Coupon coupon) {
        Integer businessId = coupon.getBusinessId();
        List<CouponCode> couponCodes=new ArrayList<>();
        for (int i = 0; i < coupon.getTotalQuantity(); i++){
            //向优惠卷卷码写入数据
            CouponCode couponCode=new CouponCode();
            couponCode.setCouponId(coupon.getId())
                .setBusinessId(businessId)
                .setStatus(0)
                .setCouponCode(UUID.randomUUID().toString())
                .setCreateTime(new Date())
                .setUpdateTime(new Date());
            couponCodes .add(couponCode);
        }
        couponCodeRepository.insertBatchCouponCode(couponCodes);
    }

    @Override
    public PageData<Coupon> getCouponList(Coupon coupon) {
        return couponRepository.selectCouponList(coupon);
    }
}
